package com.wx.daoImpl;

import java.nio.file.FileAlreadyExistsException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.wx.dao.OrderDao;
import com.wx.model.Order;
import com.wx.util.DBUtil;

public class OrderDaoImpl implements OrderDao {

	@Override
	public List<Order> selectOrders(int pageNum , int pageSize) throws Exception {
		List<Order> list = new ArrayList<>();
		Connection connection =DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("select * from orders limit ?,?");
		ps.setInt(1, (pageNum-1)*pageSize);
		ps.setInt(2, pageSize);
		ResultSet rs = ps.executeQuery();
		while(rs.next()){
			PreparedStatement ps1 = connection.prepareStatement("select bookname from books where bookid = ? ;");
			ps1.setInt(1,rs.getInt(2));
			ResultSet rs1 = ps1.executeQuery();
			if(rs1.next()){
				Order order = new Order(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8), rs.getDate(9),rs.getInt(10),rs.getInt(11),rs1.getString(1));
				list.add(order);
			}
		}
		connection.close();
		ps.close();
		rs.close();
		return list  ;
	}

	@Override
	public int selectOrderCount() throws Exception {
		int sum= 0;
		Connection connection =DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("select count(*) from orders");
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			sum=rs.getInt(1);
		}
		connection.close();
		ps.close();
		rs.close();
		return sum;
		
	}

	@Override
	public boolean updateOrderById(int id) throws Exception {
		boolean b=false;
		Connection connection=DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("update orders set orderstate = 1 where orderid= id; ");
		ps.setInt(1, id);
		int rs = ps.executeUpdate();
		if (rs==1) {
			b=true;
		}
		connection.close();
		ps.close();
		
		return b;
	}

}
